import router from '@/router'
import { useUserStore } from '@/stores'
import axios, { type InternalAxiosRequestConfig, type Method } from 'axios'
import { ElMessage } from 'element-plus'

// axios 实例
const service = axios.create({
  // 注意新接口是 /tj
  baseURL: 'http://geek.itheima.net/',
  timeout: 20 * 1000,
})

export interface ServiceResponse<T> {
  code: number
  msg: string
  data: T
}

// 请求工具函数封装
export const request = <T>(url: string, method: Method = 'GET', submitData?: object) => {
  // 返回 Promise
  return service.request<T, ServiceResponse<T>>({
    url: url,
    method: method,
    // []  插值表达式 动态设置 对象的键名称
    // 请求参数：GET 请求用 params，否则用 data
    [method.toUpperCase() === 'GET' ? 'params' : 'data']: submitData,
  })
}

service.interceptors.request.use(
  (config) => {
    const userStore = useUserStore()
    if (userStore.token) {
      config.headers.Authorization = `Bearer ${userStore.token}`
    }
    return config as InternalAxiosRequestConfig
  },
  (error) => {
    if (error.response) {
      ElMessage.error(error.response.data.message)
      if (error.response.status === 401) {
        const userStore = useUserStore()
        userStore.removeToken()
        router.push('/login')
      }
    } else {
      ElMessage.error('请求失败')
    }
    return Promise.reject(error)
  },
)

service.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    return Promise.reject(error)
  },
)

export default service
